﻿using ProxyViewModel.Samples.TodoList.Model;
using System.Collections.ObjectModel;
using System.Linq;
using System.Collections;
namespace ProxyViewModel.Samples.TodoList.ViewModel {

	// TaskManagerViewModel consists of two commands "AddTask" and "Complete", as you can see there is no ICommand properties to expose those to functions.
	public class TaskManagerViewModel {
		#region private members

		private readonly TasksRepository _repository = new TasksRepository();
		private ObservableCollection<TodoTask> _todoList = null;

		#endregion

		// TodoList exposes collection of todo tasks. Behind the scene TodoTask is ProxyViewModel.
		// Basically every "public & virtual" prooperty of the TodoTask is already exposed through INotifyPropertyChanged.
		public ObservableCollection<TodoTask> TodoList {
			get {
				if (_todoList == null) {
					LoadTodoList();
				}
				return _todoList;
			}
		}

		private void LoadTodoList() {
			_todoList = new ObservableCollection<TodoTask>();
			_repository.GetTodoList().ToList().ForEach(e => {
				// at this point every public & virtual property of TodoTask will follow INotifyPropertyChanged pattern
				TodoTask taskVm = ProxyViewModelFactory.CreateProxyViewModel<TodoTask>();
				taskVm.Description = e.Description;
				taskVm.IsCompleted = e.IsCompleted;
				_todoList.Add(taskVm);
			});
		}

		#region Commands

		// AddTaskCommand method is invoked whenever "Add task" buttnon is cliked in the MainWindow view
		public void AddTaskCommand(string taskDescription) {
			TodoTask task = ProxyViewModelFactory.CreateProxyViewModel<TodoTask>();
			task.Description = taskDescription;
			task.IsCompleted = false;
			_todoList.Add(task);
			Save();
		}

		// Complete method is invoked whenever "Complete selected" button is clicked in the MainWindow view and passes a list of selected TodoTasks
		public void CompleteCommand(IList selectedTasks) {
			selectedTasks.OfType<TodoTask>().ToList().ForEach(e =>  e.IsCompleted = true);
			Save();
		}

		#endregion

		private void Save() {
			_repository.Save(_todoList.Select(e => new TodoTask { IsCompleted = e.IsCompleted, Description = e.Description }).ToList());
		}
	}
}
